<template>
  <q-page class="q-pa-md">
    <!-- 查询表单 -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section>
        <div class="text-h6">公告查询</div>
      </q-card-section>
      <q-card-section>
        <q-form @submit="handleSearch" class="row q-col-gutter-md">
          <q-input
            v-model="searchForm.noticeTitle"
            label="公告标题"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-select
            v-model="searchForm.noticeType"
            label="公告类型"
            :options="noticeTypeOptions"
            outlined
            dense
            emit-value
            map-options
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-select
            v-model="searchForm.status"
            label="状态"
            :options="statusOptions"
            outlined
            dense
            emit-value
            map-options
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <div class="col-md-12 flex justify-end">
            <q-btn type="submit" color="primary" label="查询" class="q-mr-sm" />
            <q-btn @click="resetSearch" label="重置" outline color="primary" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>

    <!-- 操作按钮和表格 -->
    <q-card flat bordered>
      <q-card-section class="row items-center">
        <div class="text-h6 col">公告列表</div>
        <div class="col-auto q-gutter-sm">
          <q-btn color="primary" label="新增公告" icon="add" @click="showAddDialog" />
          <q-btn
            color="negative"
            label="批量删除"
            icon="delete"
            :disable="selected.length === 0"
            @click="confirmBatchDelete"
          />
        </div>
      </q-card-section>

      <!-- 数据表格 -->
      <q-table
        v-model:selected="selected"
        :rows="notices"
        :columns="columns"
        row-key="noticeId"
        :loading="loading"
        :pagination="pagination"
        @request="onRequest"
        selection="multiple"
        binary-state-sort
        flat
        bordered
      >
        <!-- 公告类型列 -->
        <template v-slot:body-cell-noticeType="props">
          <q-td :props="props">
            <q-badge :color="getNoticeTypeColor(props.row.noticeType)">
              {{ noticeTypeMap[props.row.noticeType] }}
            </q-badge>
          </q-td>
        </template>

        <!-- 状态列 -->
        <template v-slot:body-cell-status="props">
          <q-td :props="props">
            <q-toggle
              v-model="props.row.status"
              checked-icon="check"
              unchecked-icon="clear"
              :true-value="1"
              :false-value="0"
              color="green"
              @update:model-value="toggleStatus(props.row)"
            />
          </q-td>
        </template>

        <!-- 操作列 -->
        <template v-slot:body-cell-actions="props">
          <q-td :props="props" class="q-gutter-x-sm">
            <q-btn dense color="primary" icon="edit" @click="showEditDialog(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn dense color="negative" icon="delete" @click="confirmDelete(props.row.noticeId)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
            <q-btn dense color="secondary" icon="visibility" @click="previewNotice(props.row)">
              <q-tooltip>预览</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-dialog v-model="dialogVisible" persistent maximized>
      <q-card style="min-width: 800px">
        <q-card-section>
          <div class="text-h6">{{ isEdit ? '编辑公告' : '新增公告' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitForm" class="q-gutter-md">
            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input
                  v-model="noticeForm.noticeTitle"
                  label="公告标题"
                  :rules="[(val) => !!val || '公告标题不能为空']"
                  outlined
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="noticeForm.noticeType"
                  label="公告类型"
                  :options="noticeTypeOptions.filter((t) => t.value !== '')"
                  :rules="[(val) => !!val || '请选择公告类型']"
                  outlined
                  emit-value
                  map-options
                />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input v-model="noticeForm.createBy" label="创建人" outlined readonly />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="noticeForm.status"
                  label="状态"
                  :options="statusOptions.filter((s) => s.value !== '')"
                  outlined
                  emit-value
                  map-options
                />
              </div>
            </div>

            <q-editor
              v-model="noticeForm.noticeContent"
              min-height="300px"
              :toolbar="editorToolbar"
            />

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 预览对话框 -->
    <q-dialog v-model="previewDialog" maximized>
      <q-card>
        <q-bar class="bg-primary text-white">
          <div class="text-h6">{{ previewNoticeInfo.noticeTitle }}</div>
          <q-space />
          <q-btn dense flat icon="close" v-close-popup />
        </q-bar>

        <q-card-section>
          <div class="row q-mb-md">
            <div class="col">
              <div class="text-subtitle1">
                <q-icon name="person" class="q-mr-sm" />
                {{ previewNoticeInfo.createBy }}
              </div>
            </div>
            <div class="col-auto">
              <q-badge :color="getNoticeTypeColor(previewNoticeInfo.noticeType)">
                {{ noticeTypeMap[previewNoticeInfo.noticeType] }}
              </q-badge>
            </div>
            <div class="col-auto">
              <q-icon name="event" class="q-mr-sm" />
              {{ formatDate(previewNoticeInfo.createTime) }}
            </div>
          </div>

          <q-separator class="q-mb-md" />

          <div class="notice-content" v-html="previewNoticeInfo.noticeContent"></div>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar, date } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'select', label: '选择', field: '', align: 'center' },
  { name: 'noticeTitle', label: '公告标题', field: 'noticeTitle', align: 'left', sortable: true },
  { name: 'noticeType', label: '公告类型', field: 'noticeType', align: 'center' },
  { name: 'createBy', label: '创建人', field: 'createBy', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center', sortable: true },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'actions', label: '操作', align: 'center' },
]

// 公告类型选项
const noticeTypeOptions = [
  { label: '全部', value: '' },
  { label: '通知', value: '1' },
  { label: '公告', value: '2' },
  { label: '提醒', value: '3' },
]

// 公告类型映射
const noticeTypeMap = {
  1: '通知',
  2: '公告',
  3: '提醒',
}

// 公告类型颜色
const getNoticeTypeColor = (type) => {
  const colors = {
    1: 'blue',
    2: 'green',
    3: 'orange',
  }
  return colors[type] || 'grey'
}

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '发布', value: '1' },
  { label: '草稿', value: '0' },
]

// 富文本编辑器工具栏
const editorToolbar = [
  ['bold', 'italic', 'underline', 'strike'],
  ['quote', 'unordered', 'ordered'],
  ['undo', 'redo'],
  ['viewsource'],
  ['fullscreen'],
  ['link'],
  ['removeFormat'],
]

// 数据状态
const notices = ref([])
const selected = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const searchForm = ref({
  noticeTitle: '',
  noticeType: '',
  status: '',
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const noticeForm = ref({
  noticeId: null,
  noticeTitle: '',
  noticeType: '1',
  noticeContent: '',
  status: '1',
  createBy: 'admin', // 从登录信息获取
})

// 预览相关
const previewDialog = ref(false)
const previewNoticeInfo = ref({
  noticeId: '',
  noticeTitle: '',
  noticeType: '',
  noticeContent: '',
  createBy: '',
  createTime: '',
})

// 初始化加载数据
onMounted(() => {
  loadNotices()
})

// 加载公告列表
function loadNotices(props) {
  if (!props) {
    props = { pagination: pagination.value }
  }

  loading.value = true
  const { page, rowsPerPage } = props.pagination

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    const mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
      noticeId: (page - 1) * rowsPerPage + i + 1,
      noticeTitle: [
        '系统维护通知',
        '春节放假安排',
        '新版本功能更新',
        '安全漏洞修复提醒',
        '服务器迁移公告',
      ][i % 5],
      noticeType: ['1', '2', '1', '3', '2'][i % 5],
      noticeContent: `
        <h2>${['系统维护通知', '春节放假安排', '新版本功能更新', '安全漏洞修复提醒', '服务器迁移公告'][i % 5]}</h2>
        <p>尊敬的各位用户：</p>
        <p>${
          [
            '为了提供更好的服务，我们计划于2023年12月25日凌晨1:00-5:00进行系统维护，届时系统将无法访问。',
            '根据国家法定节假日安排，公司将于2024年2月9日至2月17日放假，2月18日正常上班。',
            '我们很高兴地宣布，系统将于2023年12月20日发布新版本，新增了多项功能，详情请查看更新日志。',
            '近期发现系统存在安全漏洞，请所有用户立即修改密码，并启用双重验证。',
            '为提高服务质量，我们计划于2023年12月28日进行服务器迁移，预计停机时间为2小时。',
          ][i % 5]
        }</p>
        <p>感谢您的理解与支持！</p>
        <p>系统管理员</p>
      `,
      status: Math.random() > 0.3 ? '1' : '0',
      createBy: ['admin', 'hr', 'tech', 'security', 'admin'][i % 5],
      createTime: new Date(Date.now() - i * 24 * 3600 * 1000).toISOString(),
    }))

    // 应用查询条件
    let filteredData = [...mockData]
    if (props.filter.noticeTitle) {
      filteredData = filteredData.filter((item) =>
        item.noticeTitle.includes(props.filter.noticeTitle),
      )
    }
    if (props.filter.noticeType) {
      filteredData = filteredData.filter((item) => item.noticeType === props.filter.noticeType)
    }
    if (props.filter.status) {
      filteredData = filteredData.filter((item) => item.status === props.filter.status)
    }

    notices.value = filteredData
    pagination.value.rowsNumber = filteredData.length
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
    loading.value = false
  }, 500)
}

// 表格请求方法
function onRequest(props) {
  loadNotices(props)
}

// 查询处理
function handleSearch() {
  pagination.value.page = 1
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 重置查询
function resetSearch() {
  searchForm.value = {
    noticeTitle: '',
    noticeType: '',
    status: '',
  }
  handleSearch()
}

// 显示新增对话框
function showAddDialog() {
  isEdit.value = false
  noticeForm.value = {
    noticeId: null,
    noticeTitle: '',
    noticeType: '1',
    noticeContent: '',
    status: '1',
    createBy: 'admin', // 从登录信息获取
  }
  dialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  noticeForm.value = {
    ...row,
  }
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isEdit.value ? '公告已更新' : '公告创建成功',
  })
  dialogVisible.value = false
  loadNotices()
}

// 切换状态
function toggleStatus(row) {
  $q.dialog({
    title: '确认',
    message: `确定要${row.status === '0' ? '发布' : '撤回'}公告 "${row.noticeTitle}"  吗？`,
    cancel: true,
  })
    .onOk(() => {
      // 这里应该是实际的API调用
      $q.notify({
        type: 'positive',
        message: `公告已${row.status === '0' ? '发布' : '撤回'}`,
      })
    })
    .onCancel(() => {
      // 取消操作时恢复原来的状态
      row.status = row.status === '0' ? '1' : '0'
    })
}

// 预览公告
function previewNotice(row) {
  previewNoticeInfo.value = {
    ...row,
  }
  previewDialog.value = true
}

// 格式化日期
function formatDate(dateString) {
  return date.formatDate(dateString, 'YYYY-MM-DD HH:mm:ss')
}

// 确认删除
function confirmDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该公告吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '公告已删除',
    })
    loadNotices()
  })
}

// 批量删除
function confirmBatchDelete() {
  if (selected.value.length === 0) return

  $q.dialog({
    title: '确认批量删除',
    message: `确定要删除选中的 ${selected.value.length}  个公告吗？此操作不可恢复！`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '已删除选中的公告',
    })
    selected.value = []
    loadNotices()
  })
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }
}

.notice-content {
  line-height: 1.6;

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin: 1em 0 0.5em 0;
    color: #333;
  }

  p {
    margin: 0.8em 0;
  }

  ul,
  ol {
    padding-left: 2em;
    margin: 0.8em 0;
  }

  a {
    color: #1976d2;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
